package bairui.international.console.web.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.sh_lianjing.json.jackson.exception.ConvertToJsonStringException;
import com.sh_lianjing.json.jackson.util.Util_Json;

import bairui.international.model.domain.jpa.TB_ProductCategory;

public class Util_ProductCategory {

	/**
	 * 测试
	 */
	public static void main(String[] args) throws ConvertToJsonStringException {
		TB_ProductCategory a1 = new TB_ProductCategory(1L);
			a1.setName("a1");
			TB_ProductCategory aa1 = new TB_ProductCategory(2L);
				aa1.setName("aa1");
				aa1.setParent(a1);
				TB_ProductCategory aaa1 = new TB_ProductCategory(21L);
					aaa1.setName("aaa1");
					aaa1.setParent(aa1);
				TB_ProductCategory aaa2 = new TB_ProductCategory(22L);
					aaa2.setName("aaa2");
					aaa2.setParent(aa1);
			TB_ProductCategory aa2 = new TB_ProductCategory(3L);
				aa2.setName("aa2");
				aa2.setParent(a1);
		//
		TB_ProductCategory b1 = new TB_ProductCategory(4L);
			b1.setName("b1");
			TB_ProductCategory bb1 = new TB_ProductCategory(5L);
				bb1.setName("bb1");
				bb1.setParent(b1);
			TB_ProductCategory bb2 = new TB_ProductCategory(6L);
				bb2.setName("bb2");
				bb2.setParent(b1);
				TB_ProductCategory bbb1 = new TB_ProductCategory(21L);
					bbb1.setName("bbb1");
					bbb1.setParent(bb2);
				TB_ProductCategory bbb2 = new TB_ProductCategory(22L);
					bbb2.setName("bbb2");
					bbb2.setParent(bb2);
		//
		List<TB_ProductCategory> srclist = new ArrayList<>(Arrays.asList(aaa1, aaa2, aa2, aa1, a1, bbb1, bbb2, b1, bb1, bb2));
		//
		List<TB_ProductCategory> newList = treeToList(srclist);
		System.out.println(Util_Json.toJson(newList, true));
	}

	/**
	 * 根据树状数据转换到列表结构
	 */
	public static List<TB_ProductCategory> treeToList(List<TB_ProductCategory> list){
		List<TB_ProductCategory> newList = new ArrayList<>();
		int deep = -1;
		treeToList(deep, list, null, newList);
		return newList;
	}
	
	private static void treeToList(int deep, List<TB_ProductCategory> list, TB_ProductCategory parent, List<TB_ProductCategory> newlist){
		List<TB_ProductCategory> cloneList = new ArrayList<>(list);
		deep++;
		for(TB_ProductCategory node : list){
			TB_ProductCategory nodeParent = node.getParent();
			if((null == parent && null == nodeParent) || (null!= parent && parent.equals(nodeParent))){
				// 为名称增加前缀
				String prefix = "";
				for(int i=0; i<deep; i++){
					prefix += "--";
				}
				node.setName(prefix + node.getName());
				//
				newlist.add(node);
				cloneList.remove(node);
				// 递归调用
				treeToList(deep, cloneList, node, newlist);
			}
		}
	}
	
}
